//
//  CashierViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/9/26.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "CashierViewController.h"
#import "FPNumberPadView.h"
//#import "CBSDK.h"
#import <CommonCrypto/CommonDigest.h>
//#import "ASIFormDataRequest.h"

//HZ
//NSString *MD5ForString(NSString *string)
//{
//    const char *cStr =[string UTF8String];
//    unsigned char result[16];
//    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
//    
//    NSMutableString *resultString = [NSMutableString string];
//    for (int i = 0; i < 16; i++) {
//        [resultString appendFormat:@"%02X", result[i]];
//    }
//    
//    return resultString;
//}
//
//static NSString *TPF_URL = @"http://116.31.92.201:38080/tpf";
//static NSString *APPCODE = @"2001111";
//static NSString *API_KEY = @"1D18BD714F0A025BE0539B001EACC747";
//static NSString *MD5_KEY = @"isI+kf51NwI=";
//static NSString *CALLBACK_URL = @"http://www.baidu.com";
//

@interface CashierViewController ()
{
    float cashierAmountFloat;
    NSString *memberCodeStr;
    NSString *guideCodeStr;
}
@property (nonatomic, copy) NSString *TPFToken;
@end

@implementation CashierViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    FPNumberPadView *numberPadView = [[FPNumberPadView alloc] initWithFrame:CGRectMake(0, 0, 948, 340)];
    numberPadView.textField = _cashierTextField;
    
    FPNumberPadView *numberPadView1 = [[FPNumberPadView alloc] initWithFrame:CGRectMake(0, 0, 948, 340)];
    numberPadView1.textField = _bankTextField;
    
    [_cashierTextField addTarget:self action:@selector(updateValueLabel:)  forControlEvents:UIControlEventEditingChanged];
    [_bankTextField addTarget:self action:@selector(updateValueLabel:)  forControlEvents:UIControlEventEditingChanged];


    [_alphaView setBackgroundColor:[Global parseColor:WESTORE_TRANSCLUCENT]];
    [_alphaView addTarget:self action:@selector(alphaViewClick) forControlEvents:UIControlEventTouchUpInside];
    
    memberCodeStr=@"";
    guideCodeStr=[Global getGuideCodeStr];
    [self requestDetail];
   //  [self getAuthToken];
    
    // Do any additional setup after loading the view from its nib.
}
-(void)requestDetail
{
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        [params setObject:_docTypeStr forKey:@"DocType"];
        [params setObject:_docNumStr forKey:@"DocNum"];
        // NSLog(@"paramsLIST====%@",params);
        [HttpRequest requestData:@"Guide/GatheringDetail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                   // NSLog(@"mmmmmmmm=%@",severDataDict.dataDict);
                    float AvgPrice=[[severDataDict.dataDict objectForKey:@"DocTotal"] floatValue]-[[severDataDict.dataDict objectForKey:@"IntegralAmount"] floatValue]-[[severDataDict.dataDict objectForKey:@"Rebate"] floatValue]-[[severDataDict.dataDict objectForKey:@"Subscription"] floatValue]-[[severDataDict.dataDict objectForKey:@"OldMaterial"] floatValue];
                    cashierAmountFloat=[[NSString stringWithFormat:@"%0.02f",AvgPrice] floatValue];//[[severDataDict.dataDict objectForKey:@"DocTotal"] floatValue];
                    NSString *AvgPriceStr=[Global floatConvertPercentile:AvgPrice];
                    _cashierAmountLabel.text=[NSString stringWithFormat:@"%@",AvgPriceStr];
                    if (cashierAmountFloat>0) {
                        _inputView.hidden=NO;
                    }
                    else
                    {
                        _inputView.hidden=YES;
                    }
                    
                    _numLabel.text=[severDataDict.dataDict objectForKey:@"DocNum"];
                 //  [self resizeLabel:_numLabel];
                    [Global resizeForLable:_numLabel WithText:_numLabel.text parentView:self.view];
                    NSString *statusStr=[severDataDict.dataDict objectForKey:@"DocStatus"];
                    _statusLabel.text=[NSString stringWithFormat:@"【%@】",statusStr];
                    if ([statusStr isEqualToString:@"未收银"]) {
                        [_statusLabel setTextColor:[Global parseStatusColor:statusStr]];
                        
                    }
                    else if ([statusStr isEqualToString:@"已取消"])
                    {
                        [_statusLabel setTextColor:[Global parseStatusColor:statusStr]];
                        
                    }
                    else if ([statusStr isEqualToString:@"已结算"])
                    {
                        [_statusLabel setTextColor:[Global parseStatusColor:statusStr]];
                        
                    }
                    CGRect statusframe=_statusLabel.frame;
                    statusframe.origin.x=_numLabel.frame.origin.x+_numLabel.frame.size.width;
                    _statusLabel.frame=statusframe;
                    
                    NSString *nameStr=@"";
                    NSString *phoneStr=@"";
                    if ([severDataDict.dataDict objectForKey:@"MemberName"]!=[NSNull null]) {
                        nameStr=[severDataDict.dataDict objectForKey:@"MemberName"];
                    }
                    if ([severDataDict.dataDict objectForKey:@"Phone"]!=[NSNull null]) {
                        phoneStr =[severDataDict.dataDict objectForKey:@"Phone"];
                    }
                    
                    // memberCodeStr=[memberCodeArray objectAtIndex:indexPath.row];
                    //  NSString *integralStr=[memberIntegralArray objectAtIndex:indexPath.row];
                   
                    memberCodeStr=[severDataDict.dataDict objectForKey:@"MemberCode"];
                    if (nameStr.length==0&&phoneStr.length==0) {
                        _memberAndPhoneLabel.text=@"会员 未填写";
                         // [self resizeLabel:_memberAndPhoneLabel];
                        [Global resizeForLable:_memberAndPhoneLabel WithText:_memberAndPhoneLabel.text parentView:self.view];
                        _gradeTagLabel.hidden=YES;
                        _gradeLabel.hidden=YES;
                        _integralLabel.hidden=YES;
                        _integralTagLabel.hidden=YES;
                        
                        if ([severDataDict.dataDict objectForKey:@"GuideName"]!=[NSNull null]) {
                            _guideNameLabel.text=[severDataDict.dataDict objectForKey:@"GuideName"];
                           // [self resizeLabel:_guideNameLabel];
                             [Global resizeForLable:_guideNameLabel WithText:_guideNameLabel.text parentView:self.view];
                        }

                
                        
                        CGRect frame1=_guideNameTagLabel.frame;
                        frame1.origin.x=_memberAndPhoneLabel.frame.origin.x+_memberAndPhoneLabel.frame.size.width+12;
                        _guideNameTagLabel.frame=frame1;
                        
                        CGRect frame2=_guideNameLabel.frame;
                        frame2.origin.x=_guideNameTagLabel.frame.origin.x+_guideNameTagLabel.frame.size.width+2;
                        _guideNameLabel.frame=frame2;

                    }
                    else
                    {
                         _memberAndPhoneLabel.text=[NSString stringWithFormat:@"%@(%@)",nameStr,phoneStr];
                        //  [self resizeLabel:_memberAndPhoneLabel];
                         [Global resizeForLable:_memberAndPhoneLabel WithText:_memberAndPhoneLabel.text parentView:self.view];
                        _gradeTagLabel.hidden=NO;
                        _gradeLabel.hidden=NO;
                        _integralLabel.hidden=NO;
                        _integralTagLabel.hidden=NO;
                        if ([severDataDict.dataDict objectForKey:@"Grade"]!= [NSNull null]&&[[severDataDict.dataDict objectForKey:@"Grade"] length]>0)
                        {
                            NSString *gradeStr=[severDataDict.dataDict objectForKey:@"Grade"];
                            _gradeLabel.text=gradeStr;
                            [_gradeLabel setBackgroundColor:[UIColor colorWithRed:195.0f/255.0f green:148.0f/255.0f blue:0 alpha:1.0]];
                            _gradeTagLabel.hidden=NO;
                            _gradeLabel.hidden=NO;
                          //  [self resizeLabel:_gradeLabel];
                             [Global resizeForLable:_gradeLabel WithText:_gradeLabel.text parentView:self.view];
                            //_memberGradeLabel.text=[severDataDict.dataDict objectForKey:@"Grade"];
                        }
                        else
                        {
                            _gradeLabel.text=@"";
                            [_gradeLabel setBackgroundColor:[UIColor clearColor]];
                        }
                        
                        
                        CGRect frame=_gradeTagLabel.frame;
                        frame.origin.x=_memberAndPhoneLabel.frame.origin.x+_memberAndPhoneLabel.frame.size.width+12;
                        _gradeTagLabel.frame=frame;
                        
                        CGRect frame1=_gradeLabel.frame;
                        frame1.origin.x=_gradeTagLabel.frame.origin.x+_gradeTagLabel.frame.size.width+2;
                        _gradeLabel.frame=frame1;
                        
                        CGRect frame2=_integralTagLabel.frame;
                        frame2.origin.x=_gradeLabel.frame.origin.x+_gradeLabel.frame.size.width+12;
                        _integralTagLabel.frame=frame2;
                        // }
                        
                        if ([severDataDict.dataDict objectForKey:@"Integral"]!= [NSNull null] )
                        {
                            _integralLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"Integral"] integerValue]];
                        //    [self resizeLabel:_integralLabel];
                            [Global resizeForLable:_integralLabel WithText:_integralLabel.text parentView:self.view];
                            CGRect frame=_integralLabel.frame;
                            frame.origin.x=_integralTagLabel.frame.origin.x+_integralTagLabel.frame.size.width+2;
                            _integralLabel.frame=frame;
                            
                            CGRect frame1=_guideNameTagLabel.frame;
                            frame1.origin.x=_integralLabel.frame.origin.x+_integralLabel.frame.size.width+12;
                            _guideNameTagLabel.frame=frame1;
                            
                            CGRect frame2=_guideNameLabel.frame;
                            frame2.origin.x=_guideNameTagLabel.frame.origin.x+_guideNameTagLabel.frame.size.width+2;
                            _guideNameLabel.frame=frame2;
                        }
                        if ([severDataDict.dataDict objectForKey:@"GuideName"]!=[NSNull null]) {
                            _guideNameLabel.text=[severDataDict.dataDict objectForKey:@"GuideName"];
                          //  [self resizeLabel:_guideNameLabel];
                             [Global resizeForLable:_guideNameLabel WithText:_guideNameLabel.text parentView:self.view];
                        }
                        

                        
                        
                    }
                    
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        
                                               [Global loginViewController:self noteStr:requestResultStr];
                        ///  [Global loginViewController:self];
                    }
                    
                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
}
//- (void)getAuthToken
//{
//    // 先取token, 做预下单时需要用到. 可以放在第三方登录之后.
//    [[CBSDK sharedInstance] authWithAPIKey:API_KEY resultBlock:^(NSString *token, NSString *errorCode, NSString *errorMessage) {
//        if (errorCode == nil) {
//            self.TPFToken = token;
//            //  [self textViewAppendFormat:@"得到 TPFToken:%@\n", token];
//        } else {
//            // [self textViewAppendFormat:@"errorCode:%@, errorMessage:%@\n", errorCode, errorMessage];
//        }
//    }];
//}
//
-(IBAction)confirmCashierClick:(id)sender
{
    
    //  以下为盒子支付功能
//    if ([_bankTextField.text floatValue]>0) {
//    
//    if ([Global getLoginToken].length>0) {
//        
//        
//        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
//        
//        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
//        [params setObject:[Global getLoginToken] forKey:@"Token"];
//        
//        [params setObject:_numLabel.text forKey:@"DocNum"];
//        [params setObject:self.TPFToken forKey:@"iboxpayToken"];
//        [params setObject:_docTypeStr forKey:@"DocType"];
//        [params setObject:_bankTextField.text forKey:@"OrderAmount"];
//        //  NSLog(@"lllllARAM===%@",params);
//        [HttpRequest requestData:@"Guide/Iboxpay_Gather" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
//            if (isSuccess) {
//                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                    [Global hideProgressHUDInternal:self.view];
//                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                    [Global showTextHudSub:requestResultStr view:self.view];
//                    
//                    // NSLog(@"hz=====%@",severDataDict.dataDict);
//                    int orderAmount = [[severDataDict.dataDict objectForKey:@"orderAmount"] intValue];
//                    static NSDateFormatter *dateFormatter = nil;
//                    if (dateFormatter == nil) {
//                        dateFormatter = [[NSDateFormatter alloc] init];
//                    }
//                    dateFormatter.dateFormat = @"yyyyMMddHHmmss";
//                    
//                    NSString *orderTime = [dateFormatter stringFromDate:[NSDate date]];
//                    // NSString *outTradeNo = orderTime; // 第三方订单号实际上是由第三方后台生成.
//                    
//                    NSString *outTradeNo =[severDataDict.dataDict objectForKey:@"TradeNo"];
//                    
//                    NSString *signParams = [NSString stringWithFormat:@"_inputCharset=UTF-8&callbackUrl=%@&orderAmount=%d&orderNo=%@&orderTime=%@&outTradeNo=%@&token=%@", CALLBACK_URL, orderAmount, outTradeNo, orderTime, outTradeNo, self.TPFToken];
//                    
//                    // NSLog(@"signParams====%@",signParams);
//                    NSString *signResult = MD5ForString([NSString stringWithFormat:@"%@%@", signParams, MD5_KEY]);
//                    NSString *requestURLString = [NSString stringWithFormat:@"%@/order/create.htm/%@?%@&signType=MD5&sign=%@", TPF_URL, APPCODE, signParams, signResult];
//                    NSLog(@"signParams:%@ \n, signResult:%@\n, signURL:%@", signParams, signResult, requestURLString);
//                    
//                    [[CBSDK sharedInstance] startPaymentWithViewController:self APIKey:API_KEY appCode:APPCODE outTradeNo:outTradeNo tradeNo:@"" orderAmount:orderAmount tradeType:CBTradeTypePayment completion:^(NSString *cbTradeNo, NSString *errorCode, NSString *errorMessage) {
//                        if (errorCode == nil) {
//                          //  isLoad=YES;
//                            
//                           // [self hzSuccess];
//                            if ([self.delegate respondsToSelector:@selector(CashierSuccess)]) {
//                                
//                                [self.delegate CashierSuccess];
//                            }
//
//                        }
//                        else {
//                            
//                            
//                            //  [self textViewAppendFormat:@"支付失败, errorCode: %@, errorMessage: %@ \n\n", errorCode, errorMessage];
//                        }
//                    }];
//                    
//                }
//                else
//                {
//                    [Global hideProgressHUDInternal:self.view];
//                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                    //  [Global showTextHud:requestResultStr view:self.view];
//                    [Global showTextHudSub:requestResultStr view:self.view];
//                }
//            }
//            else
//            {
//                [Global hideProgressHUDInternal:self.view];
//                [Global showTextHudSub:@"连接失败" view:self.view];
//            }
//        }];
//        
//    }
//  }
//    else
//    {
//            if ([Global getLoginToken].length>0) {
//                [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
//        
//                NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
//                [params setObject:[Global getLoginToken] forKey:@"Token"];
//        
//                [params setObject:_numLabel.text forKey:@"DocNum"];
//                [params setObject:guideCodeStr forKey:@"GuideCode"];
//                [params setObject:memberCodeStr forKey:@"MemberCode"];
//                [params setObject:_docTypeStr forKey:@"DocType"];
//        
//                [params setObject:_cashierTextField.text forKey:@"Cash"];
//                [params setObject:_bankTextField.text forKey:@"UnionPay"];
//                        //  NSLog(@"lllllARAM===%@",params);
//                [HttpRequest requestData:@"Guide/Gathering" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
//                    if (isSuccess) {
//                        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                            [Global hideProgressHUDInternal:self.view];
//                            NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                            [Global showTextHudSub:requestResultStr view:self.view];
//                            _cashierTextField.text=@"";
//                            _bankTextField.text=@"";
//                            if ([self.delegate respondsToSelector:@selector(CashierSuccess)]) {
//        
//                                [self.delegate CashierSuccess];
//                            }
//        
//                        }
//                        else
//                        {
//                            [Global hideProgressHUDInternal:self.view];
//                            NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                            //  [Global showTextHud:requestResultStr view:self.view];
//                            [Global showTextHudSub:requestResultStr view:self.view];
//                            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
//        
//                                [Global loginViewController:self noteStr:requestResultStr];
//                                //  [Global loginViewController:self];
//                            }
//                            
//                        }
//                    }
//                    else
//                    {
//                        [Global hideProgressHUDInternal:self.view];
//                        [Global showTextHudSub:@"连接失败" view:self.view];
//                    }
//                }];
//                
//            }
//
//    }
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        
        [params setObject:_numLabel.text forKey:@"DocNum"];
        [params setObject:guideCodeStr forKey:@"GuideCode"];
        [params setObject:memberCodeStr forKey:@"MemberCode"];
        [params setObject:_docTypeStr forKey:@"DocType"];
        
        [params setObject:_cashierTextField.text forKey:@"Cash"];
        [params setObject:_bankTextField.text forKey:@"UnionPay"];
        //  NSLog(@"lllllARAM===%@",params);
        [HttpRequest requestData:@"Guide/Gathering" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    _cashierTextField.text=@"";
                    _bankTextField.text=@"";
                    if ([self.delegate respondsToSelector:@selector(CashierSuccess)]) {
                        
                        [self.delegate CashierSuccess];
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        
                        [Global loginViewController:self noteStr:requestResultStr];
                        //  [Global loginViewController:self];
                    }
                    
                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
    


}

-(void)updateValueLabel:(UITextField *)sender
{
    
    if (sender==_bankTextField) {
        if ([_bankTextField.text floatValue]<cashierAmountFloat) {
            _cashierTextField.text=[NSString stringWithFormat:@"%0.02f",cashierAmountFloat-[_bankTextField.text floatValue]];
                }
        else
        {
            
        }
        
    }
    if (sender==_cashierTextField) {
        _bankTextField.text=[NSString stringWithFormat:@"%0.02f",cashierAmountFloat-[_cashierTextField.text floatValue]];
        }
   
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField==_cashierTextField)
    {
       
        _bankTextField.text=@"";
        
        _cashierTextField.text=[NSString stringWithFormat:@"%0.02f",cashierAmountFloat];
        
    }
    else if (textField==_bankTextField)
    {
        
        _cashierTextField.text=@"";
        // _bankTextField.text=[NSString stringWithFormat:@"%0.02f",balanceAmountFloat];
        
            
            
    _bankTextField.text=[NSString stringWithFormat:@"%0.02f",cashierAmountFloat];
    }
   return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
        if (textField==_cashierTextField||textField==_bankTextField) {
            if (([_cashierTextField.text floatValue]>cashierAmountFloat)||([_bankTextField.text floatValue]>cashierAmountFloat)) {
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的金额已大于支付金额，请重新填写" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                _cashierTextField.text=@"";
                
                _bankTextField.text=@"";
            }
        }
}

-(void)alphaViewClick
{
    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }

    if ([self.delegate respondsToSelector:@selector(CashierAlphaViewClick)]) {
        [self.delegate CashierAlphaViewClick];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
